//
//  AppDelegate.swift
//  剂查查
//
//  Created by shoubin tao on 2024/11/30.
//  Copyright © 2024 shipin. All rights reserved.
//

import UIKit
import CommonTools
import IQKeyboardManagerSwift
import CJMobileAd

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        configAds()
        setupWXSDK()
        setupKeyboardManager()
        
        return true
    }
    
    func setupWXSDK(){
        let impl = XWWeChatOpenSDKBridgeProtocolImpl.shared
        impl.startLog { log in
            XWLog(value: "微信SDKlog：\(log)")
        }
        impl.registerApp()
    }
    
    @MainActor func setupKeyboardManager(){
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.resignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
    }
    
    func configAds(){
        
        CJADManager.configure("2192b5b29d24b12b") { success, error in
            if success {
                print("ad注册成功")
            }
        }
        CJADManager.openDebugLog()
    }

    func applicationWillResignActive(_ application: UIApplication) {}

    func applicationDidEnterBackground(_ application: UIApplication) {}

    func applicationWillEnterForeground(_ application: UIApplication) {}

    func applicationDidBecomeActive(_ application: UIApplication) {}

    func applicationWillTerminate(_ application: UIApplication) {}

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        XWLog(value: "openUrl:\(url)")
        var result = false
        let impl = XWWeChatOpenSDKBridgeProtocolImpl.shared
        result = impl.handleOpen(url: url)
        return result
    }
    
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([any UIUserActivityRestoring]?) -> Void) -> Bool {
        var result = false
        let impl = XWWeChatOpenSDKBridgeProtocolImpl.shared
        result = impl.handleOpenUniversalLink(userActivity: userActivity)
        return result
    }
}

extension UIApplication {
    var keyWindow: UIWindow? {
        if #available(iOS 13.0, *) {
            for scene in connectedScenes where scene.activationState == .foregroundActive {
                if let windowScene = scene as? UIWindowScene {
                    return windowScene.windows.filter({$0.isKeyWindow}).first
                }
            }
        }
        return self.delegate?.window ?? nil
    }
}
